<template>
  <div class="questions-new-container">
    <div class="app-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>试题录入</span>
        </div>
        <div class="form-container">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="学科" prop="subjectID">
              <el-select
                v-model="form.subjectID"
                @change="subjectIDChange"
                placeholder="请选择学科"
              >
                <el-option
                  v-for="item in subjectArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录" prop="catalogID">
              <el-select v-model="form.catalogID" placeholder="请选择">
                <el-option
                  v-for="item in catalogArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业" prop="enterpriseID">
              <el-select v-model="form.enterpriseID" placeholder="请选择企业">
                <el-option
                  v-for="item in enterpriseArr"
                  :key="item.id"
                  :label="item.company"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="城市" class="form-region-city" prop="province">
              <el-select
                v-model="form.province"
                @change="provincesChange"
                placeholder="请选择地市"
                class="form-region"
              >
                <el-option
                  :label="item"
                  :value="item"
                  v-for="(item, index) in provinces"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item class="form-region-city form-city-label" prop="city">
              <el-select
                v-model="form.city"
                placeholder="请选择区县"
                class="form-city"
              >
                <el-option
                  v-for="(item, index) in city"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="方向" prop="direction">
              <el-select v-model="form.direction" placeholder="请选择方向">
                <el-option
                  v-for="(item, index) in directionArr"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题型" prop="questionType">
              <el-radio-group
                v-model="form.questionType"
                @change="questionTypeChange"
              >
                <el-radio
                  v-for="item in questionTypeArr"
                  :key="item.value"
                  :label="`${item.value}`"
                >
                  {{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="难度" prop="difficulty">
              <el-radio-group v-model="form.difficulty">
                <el-radio
                  v-for="item in difficultyArr"
                  :key="item.value"
                  :label="`${item.value}`"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="题干" prop="question">
              <TinymceEdit :value="form.question" v-model="form.question" />
            </el-form-item>
            <el-form-item label="选项" v-if="form.questionType !== '3'" prop="options">
              <div class="options-container">
                <div class="options-left">
                  <el-radio-group
                    v-model="optionsRadio"
                    @change="optionsRadioChange"
                    v-if="form.questionType === '1'"
                  >
                    <el-radio
                      v-for="(item, index) in form.options"
                      :key="index"
                      :label="index"
                      class="options-left-radio"
                    >
                      {{ item.code }}
                    </el-radio>
                  </el-radio-group>
                  <el-checkbox-group
                    v-model="optionsCheckArr"
                    v-else-if="form.questionType === '2'"
                    @change="optionsCheckChange"
                  >
                    <el-checkbox
                      v-for="(item, index) in form.options"
                      :key="index"
                      :label="index"
                      class="options-left-radio"
                      >{{ item.code }}</el-checkbox
                    >
                  </el-checkbox-group>
                </div>
                <div class="options-center">
                  <el-input
                    v-for="(item, index) in form.options"
                    :key="index"
                    v-model="form.options[index].title"
                    class="options-input"
                  ></el-input>
                </div>
                <div class="options-right">
                  <UploadImg
                    v-for="(item, index) in form.options"
                    :key="index"
                    v-model="item.img"
                    :index="index"
                    @closeImg="closeImg"
                  />
                </div>
              </div>
              <el-button
                type="danger"
                @click="addOptions"
                :disabled="form.questionType !== '2' || form.options.length === 7"
                >+增加选项与答案</el-button
              >
            </el-form-item>
            <el-form-item label="解析视频" class="form-videoURL" prop="videoURL">
              <el-input
                v-model="form.videoURL"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
            <el-form-item label="答案解析" prop="answer">
              <!-- answer -->
              <TinymceEdit :value="form.answer" v-model="form.answer" />
            </el-form-item>
            <el-form-item label="题目备注" prop="remarks">
              <!-- <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 2 }"
                placeholder="请输入内容"
                v-model="form.remarks"
              >
              </el-input> -->
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="form.remarks"
                show-word-limit
                style="width: 400px"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="试题标签" prop="tags">
              <el-select
                v-model="form.tags"
                placeholder="请选择"
                multiple
                filterable
                allow-create
                default-first-option
              >
                <el-option
                  v-for="item in tagsArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="btnSubmit">确认提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// import map from '@/api/base/map'
import { provinces, citys } from '@/api/hmmm/citys'
import { add, detail, update } from '@/api/hmmm/questions'
import { simple as catalogIDsimple } from '@/api/hmmm/directorys'
import { simple as subjectIDsimple } from '@/api/hmmm/subjects'
import { list as enterpriseIDlist } from '@/api/hmmm/companys'
import { simple as tagsSimple } from '@/api/hmmm/tags'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import TinymceEdit from '@/components/TinymceEditor/index.vue'
import UploadImg from '@/components/UploadImg/index.vue'
export default {
  components: {
    TinymceEdit,
    UploadImg
  },
  data () {
    const checkOptions = (rule, value, callback) => {
      console.log(value)
      let isRight = false
      let title = false
      value.forEach((item, index) => {
        if (item.isRight) {
          isRight = true
        }
        if (!item.title) {
          title = true
        }
      })
      if (!isRight) return callback(new Error('请选择答案'))
      if (title) return callback(new Error('请输入选项内容'))
      callback()
    }
    return {
      rules: {
        subjectID: [
          {
            required: true,
            message: '请选择学科',
            trigger: ['blur', 'change']
          }
        ],
        catalogID: [
          {
            required: true,
            message: '请选择',
            trigger: ['blur', 'change']
          }
        ],
        enterpriseID: [
          {
            required: true,
            message: '请选择企业',
            trigger: ['blur', 'change']
          }
        ],
        province: [
          {
            required: true,
            message: '请选择地区',
            trigger: ['blur', 'change']
          }
        ],
        city: [
          {
            required: true,
            message: '请选择区县',
            trigger: ['blur', 'change']
          }
        ],
        direction: [
          {
            required: true,
            message: '请选择方向',
            trigger: ['blur', 'change']
          }
        ],
        questionType: [
          {
            required: true,
            message: '请选择题型',
            trigger: ['blur', 'change']
          }
        ],
        difficulty: [
          {
            required: true,
            message: '请选择困难程度',
            trigger: ['blur', 'change']
          }
        ],
        answer: [
          {
            required: true,
            message: '请输入答案',
            trigger: ['blur', 'change']
          }
        ],
        videoURL: [
          {
            required: true,
            message: '请输入解析视频',
            trigger: ['blur', 'change']
          }
        ],
        remarks: [
          {
            required: true,
            message: '请输入题目备注',
            trigger: ['blur', 'change']
          }
        ],
        question: [
          {
            required: true,
            message: '请输入题干',
            trigger: ['blur', 'change']
          }
        ],
        tags: [
          {
            required: true,
            message: '请选择标签',
            trigger: ['blur', 'change']
          }
        ],
        options: [
          {
            required: true,
            validator: checkOptions,
            // message: '请选择标签',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 数据表单
      form: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 市
        province: '',
        // 区县
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        options: [
          {
            code: 'A :',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B :',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C :',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D :',
            title: '',
            img: '',
            isRight: false
          }
        ],
        // 解析视频
        videoURL: '',
        answer: '',
        // 题目备注
        remarks: '',
        // 标签
        tags: []
      },
      // 市
      provinces: provinces(),
      // 区 县
      city: [],
      // 学科列表
      subjectArr: [],
      // 目录列表
      catalogArr: [],
      // 企业列表
      enterpriseArr: [],
      // 方向列表
      directionArr: direction,
      // 题型数组
      questionTypeArr: questionType,
      // 难度数组
      difficultyArr: difficulty,
      optionsRadio: 0,
      options: [
        //   {
        //     check: false,
        // }
      ],
      // 标签数组
      tagsArr: [],
      // 多选框绑定的数组
      optionsCheckArr: [],
      // 增加选项数组
      letterArr: ['A :', 'B :', 'C :', 'D :', 'E :', 'F :', 'G :'],
      // 路由参数id
      queryId: this.$route.query.id,
      // 保存单选数组
      userRadioArr: [
        {
          code: 'A :',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'B :',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C :',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D :',
          title: '',
          img: '',
          isRight: false
        }
      ],
      // 保存多选数组
      userCheckArr: [
        {
          code: 'A :',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'B :',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C :',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D :',
          title: '',
          img: '',
          isRight: false
        }
      ]
    }
  },
  created () {
    // console.log(map)
    // const city = {}
    // for (let x = 110000; x < 830000; x += 100) {
    //   if (map[x]) {
    //     city[x] = map[x]
    //   }
    // }
    // this.city = city
    subjectIDsimple().then((data) => {
      console.log('学科列表', data)
      this.subjectArr = data.data
    })

    enterpriseIDlist().then((data) => {
      console.log('企业列表', data)
      this.enterpriseArr = data.data.items
    })
    // 修改
    if (this.queryId) {
      // update
      // console.log('跳转传参')
      detail({ id: this.queryId }).then(data => {
        console.log('跳转传参数据', data)
        this.form = data.data
        this.subjectIDChange(this.form.subjectID)
        this.form.tags = this.form.tags.split(',')
        switch (this.form.questionType) {
          case '1':
            this.form.options.forEach((item, index) => {
              if (item.isRight === 1) this.optionsRadio = index
            })
            this.userRadioArr = this.form.options
            break
          case '2':
            this.userCheckArr = this.form.options
            this.optionsCheckArr = this.form.options.map((item, index) => {
              if (item.isRight) return index
            })
            break
        }
      })
    }
    // console.log('query:', this.$route.query)
  },
  methods: {
    // 市改变获取对应的区县
    provincesChange (name) {
      this.city = citys(name)
    },
    //
    subjectIDChange (id) {
      catalogIDsimple({ subjectID: id }).then((data) => {
        console.log('目录列表', data)
        this.catalogArr = data.data
      })
      tagsSimple({ subjectID: id }).then((data) => {
        console.log('标签列表', data)
        this.tagsArr = data.data
        console.log('标签列表', this.tagsArr)
      })
    },
    // 单选框按钮改变
    optionsRadioChange (index) {
      console.log('option索引', index)
      for (let x = 0; x < 4; x++) {
        this.$set(this.form.options[x], 'isRight', false)
      }
      this.$set(this.form.options[index], 'isRight', true)
      // this.optionsRadio = index
    },
    // 题型改变
    questionTypeChange (value) {
      console.log(value)
      switch (this.form.questionType) {
        case '1':
          this.userCheckArr = this.form.options
          this.form.options = this.userRadioArr
          break
        case '2':
          this.userRadioArr = this.form.options
          this.form.options = this.userCheckArr
          break
      }
    },
    // 多选框改变
    optionsCheckChange (value) {
      console.log('check改变的数组', value)
      for (let x = 0; x < this.form.options; x++) {
        this.$set(this.form.options[x], 'isRight', false)
      }
      value.forEach((item) => {
        this.$set(this.form.options[item], 'isRight', true)
      })
    },
    // 增加新的多选框选项
    addOptions () {
      const index = this.form.options.length
      this.form.options.push({
        code: this.letterArr[index],
        title: null,
        img: null,
        isRight: false
      })
    },
    // 确认表单内容
    btnSubmit () {
      this.$refs.form.validate((vali) => {
        if (vali) {
          this.form.tags = this.form.tags.join(',')
          // this.form.questionType = String(this.form.questionType)
          // this.form.difficulty = String(this.form.difficulty)
          if (this.queryId) {
            update(this.form).then((data) => {
              console.log('添加题', data)
              this.$notify({
                title: '成功',
                message: '修改题目成功',
                type: 'success'
              })
              // this.form.questionType = 1
              // this.form.difficulty = 1
              // this.form.tags = []
              this.$router.push({
                path: '/questions/list'
              })
            })
          } else {
            add(this.form).then((data) => {
              console.log('添加题', data)
              this.$notify({
                title: '成功',
                message: '添加题库成功',
                type: 'success'
              })
              // this.form.questionType = 1
              // this.form.difficulty = 1
              // this.form.tags = []
              this.$router.push({
                path: '/questions/list'
              })
            })
          }
        }
      })
    },
    closeImg (index) {
      console.log('要删除的图片索引', index)
      this.form.options[index].img = ''
    }
  }
}
</script>

<style scoped lang='scss'>
.form-container {
  margin-left: 55px;
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
.disabled .el-upload--picture-card {
  display: none;
}
.options-container {
  display: flex;
  width: 410px;
  min-height: 310px;
  margin-top: -10px;
  .options-left .el-radio-group,
  .options-left .el-checkbox-group,
  .options-center,
  .options-right {
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    height: 100%;
  }
  .options-left {
    width: 50px;
    height: 100%;
    .el-radio-group {
      .options-left-radio {
        display: flex;
        align-items: center;
        height: 70px;
        height: 80px;
        // height: 60px;
        .el-radio__input {
          width: 14px;
          height: 15px;
        }
      }
    }
    .el-checkbox-group {
      .el-checkbox {
        display: flex;
        align-items: center;
        // height: 60px;
        height: 70px;
        height: 80px;
      }
    }
  }
  .options-center {
    width: 240px;

    .options-input ::v-deep .el-input__inner {
      width: 240px;
    }
    .options-input {
      display: flex;
      align-items: center;
      // height: 60px;
      height: 70px;
      height: 80px;
    }
  }
  .options-right {
    width: 100px;
    margin-left: 5px;
    .avatar-uploader {
      display: flex;
      align-items: center;
    }
  }
}
// 修改下拉框display
.form-province {
  display: inline-block;
}
// 修改选择框宽度
.el-select,
.form-videoURL .el-input {
  width: 400px;
}
.form-region-city {
  display: inline-block;
}
.form-city-label ::v-deep .el-form-item__content {
  margin-left: 2px !important;
  // margin-left: 0;
}
.form-region-city .el-select {
  width: 197px;
}
.form-city {
  margin-left: 5px;
}
</style>
